<?php

namespace App\Http\Controllers\Admin;

use Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\RoleRequest;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    public function index(Request $request, Role $role)
    {
        $content = Admin::content()
                        ->title('角色')
                        ->desc('所有角色')
                        ->content($this->table());

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    protected function table()
    {
        $table = Admin::table(Role::class)
                      ->columns([
                          'id'           => '编号',
                          'display_name' => '角色名',
                          'name'         => '标志',
                          'created_at'   => '添加时间',
                          'updated_at'   => '最后更新',
                      ]);

        return $table;
    }

    public function create(Request $request, Role $role)
    {
        $content = Admin::content()
                        ->title('角色')
                        ->desc('添加角色')
                        ->content($this->form($role));

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    public function edit(Request $request, Role $role)
    {
        $content = Admin::content()
                        ->title('角色')
                        ->desc('编辑角色')
                        ->content($this->form($role)->edit());

        return response()->json([
            'status'  => true,
            'content' => $content,
        ]);
    }

    protected function form(Role $role = null)
    {
        $form = Admin::form($role);

        $form->input('display_name', '角色名')->required();
        $form->input('name', '标志')->required();

        $form->multipleSelect('permissions', '权限')
             ->options(Permission::pluck('display_name', 'id')->toArray())
             ->listStyle('h')
             ->placeholder('选择权限');

        return $form;
    }

    public function store(RoleRequest $request, Role $role)
    {
        return $this->form($role)->store();
    }

    public function destroy(Role $role)
    {
        return $this->form($role)->destroy();
    }

    public function update(RoleRequest $request, Role $role)
    {
        return $this->form($role)->update();
    }
}
